package com.dream.dk.Calorie;

import java.net.SocketTimeoutException;
import java.util.List;

import org.apache.commons.httpclient.ConnectTimeoutException;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpConnectionManager;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.SimpleHttpConnectionManager;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
import org.seasar.framework.log.Logger;

import com.dream.dk.dto.diet.CaloriesInfoDto;

public class CalorieApiUtils {
	private static Logger logger = Logger.getLogger(CalorieApiUtils.class);

	private static String URL_CALORIE_API = "http://24th.jp/test/api_cal.php?submit=on";
	private static final int connectionTimeout = 10000;
	private static final int requestTimeout = 5000;

	/**
	 * カロリーのAPIを実行
	 * 
	 * @param requestParameter
	 * @return
	 */
	public static List<CaloriesInfoDto> getCaloriesFromAPI(
			String requestParameter) {

		// リクエストURL作成
		String url = URL_CALORIE_API + requestParameter;

		// APIの実行
		String calorieResult = apiExecute(url);
		
		CalorieParser parser = new CalorieParser();

		return parser.parseResponse(calorieResult);

	}

	/**
	 * 指定されたAPIを実行
	 * 
	 * @param url
	 * @return
	 */
	private static String apiExecute(String url) {
		HttpConnectionManagerParams params = new HttpConnectionManagerParams();
		params.setConnectionTimeout(connectionTimeout);
		params.setSoTimeout(requestTimeout);

		HttpConnectionManager manager = new SimpleHttpConnectionManager();
		manager.setParams(params);

		HttpMethod httpget = null;
		try {
			HttpClient httpClient = new HttpClient(manager);
			logger.debug("call api [" + url + "]");

			httpget = new GetMethod(url);
			int status = httpClient.executeMethod(httpget);
			if(HttpStatus.SC_OK != status){
				String errorBody = httpget.getResponseBodyAsString();
				logger.warn("api returnd illegal status[" + status +"] body [" + errorBody+ "]");
				return null;
			}
			
			//レスポンスを返却
			return httpget.getResponseBodyAsString();
			
		} catch (ConnectTimeoutException e) {
			//接続に失敗
			logger.warn("api connection timeout occured. url is [" + url +"]", e);
			return null;
		} catch (SocketTimeoutException e) {
			//要求タイムアウト
			logger.warn("api socket timeout occured. url is [" + url +"]", e);
			return null;
		} catch (Exception e) {
			logger.warn("api exception occured. url is [" + url +"]", e);
			return null;
		}finally{
			if(httpget !=null){
				httpget.releaseConnection();
			}
		}
	}
}
